package net.loyintean.pearlshell.base.service;

import java.awt.image.BufferedImage;

import sun.misc.BASE64Encoder;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.imageio.ImageIO;

import com.google.zxing.common.BitMatrix;

@SuppressWarnings("restriction")
public final class MatrixToImageWriter {
	private static final int BLACK = 0xFF000000;
	private static final int WHITE = 0xFFFFFFFF;

	private MatrixToImageWriter() {
	}

	public static BufferedImage toBufferedImage(BitMatrix matrix) {
		int width = matrix.getWidth();
		int height = matrix.getHeight();
		BufferedImage image = new BufferedImage(width, height,
				BufferedImage.TYPE_INT_RGB);
		for (int x = 0; x < width; x++) {
			for (int y = 0; y < height; y++) {
				image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
			}
		}
		return image;
	}

	public static void writeToFile(BitMatrix matrix, String format, File file)
			throws IOException {
		BufferedImage image = toBufferedImage(matrix);
		if (!ImageIO.write(image, format, file)) {
			throw new IOException("Could not write an image of format "
					+ format + " to " + file);
		}
	}

	public static void writeToStream(BitMatrix matrix, String format,
			OutputStream stream) throws IOException {
		BufferedImage image = toBufferedImage(matrix);

		if (!ImageIO.write(image, format, stream)) {
			throw new IOException("Could not write an image of format "
					+ format);
		}
	}

	public static String writeToBase64(BitMatrix matrix, String format,
			String fileName) throws IOException {

		// 将图片文件转化为字节数组字符串，并对其进行Base64编码处理
		File imgFile = new File(fileName);
		if (!imgFile.exists()) {
			imgFile.createNewFile();
		}

		writeToFile(matrix, format, imgFile);

		byte[] data = null;
		// 读取图片字节数组
		InputStream in = new FileInputStream(imgFile);
		data = new byte[in.available()];
		in.read(data);
		in.close();
		// 对字节数组Base64编码
		BASE64Encoder encoder = new BASE64Encoder();
		String result = encoder.encode(data);

		imgFile.delete();
		
//		try {    
//            bi = ImageIO.read(f);    
//            ByteArrayOutputStream baos = new ByteArrayOutputStream();    
//            ImageIO.write(bi, "jpg", baos);    
//            byte[] bytes = baos.toByteArray();    
//                
//            return encoder.encodeBuffer(bytes).trim();    
//        } catch (IOException e) {    
//            e.printStackTrace();    
//        }    

		return result;// 返回Base64编码过的字节数组字符串
	}

	/** 修剪二维码白边
	 * <p>
	 * matrix据说自己不提供设置白边的配置属性。因此重绘制一遍
	 * 
	 * @param matrix
	 * @param margin
	 * @return */
	public static final BitMatrix updateBit(BitMatrix matrix, int margin) {

		int tempM = margin * 2;

		int[] rec = matrix.getEnclosingRectangle(); // 获取二维码图案的属性

		int resWidth = rec[2] + tempM;

		int resHeight = rec[3] + tempM;

		BitMatrix resMatrix = new BitMatrix(resWidth, resHeight); // 按照自定义边框生成新的BitMatrix

		resMatrix.clear();

		for (int i = margin; i < resWidth - margin; i++) { // 循环，将二维码图案绘制到新的bitMatrix中

			for (int j = margin; j < resHeight - margin; j++) {

				if (matrix.get(i - margin + rec[0], j - margin + rec[1])) {

					resMatrix.set(i, j);

				}

			}

		}

		return resMatrix;

	}
}